---@class components
---@field webbert_seedbox component_webbert_seedbox

local function on_info(self, value)
    self.inst.replica.webbert_seedbox.info:set(value)
end

---@class component_webbert_seedbox
---@field inst ent
---@field map table<PrefabID,integer> # 种子: 数量
---@field info string # 'tomato_seeds|40'
local webbert_seedbox = Class(
---@param self component_webbert_seedbox
---@param inst ent
function(self, inst)
    self.inst = inst
    self.info = 'tomato_seeds|0'
    self.map = {}
end,
nil,
{
    info = on_info,
})

function webbert_seedbox:OnSave()
    local sav = {}
    for k,v in pairs(self.map) do
        sav[k] = v
    end
    return sav
end

-- function webbert_seedbox:OnLoad(data)
--     local encode_str = ''
--     for k,v in pairs(data or {}) do
--         self.map[k] = v
--         if encode_str ~= '' then
--             encode_str = encode_str .. '|'
--         end
--         encode_str = encode_str .. k .. '|' .. v
--     end
--     self.info = encode_str
-- end

function webbert_seedbox:OnLoad(data)
    local parts = {}
    for k, v in pairs(data or {}) do
        self.map[k] = v
        table.insert(parts, k)
        table.insert(parts, tostring(v))
    end
    self.info = table.concat(parts, "|")
end

---获取种子
---@param prefab string
---@param num integer
function webbert_seedbox:GetSeeds(prefab,num)
    self.map[prefab] = (self.map[prefab] or 0) + num
    self.info = prefab .. '|' .. self.map[prefab]
end

---拿出种子
---@param prefab any
---@return ent|nil
function webbert_seedbox:FetchSeeds(prefab)
    local cur_num = self.map[prefab] or 0
    if cur_num > 0 then
        local seeds = SpawnPrefab(prefab)
        local maxsize = seeds.components.stackable and seeds.components.stackable.maxsize or 1
        local fetch_num = 1 -- 最少也有1个
        if maxsize > 1 then
            fetch_num = math.min(cur_num,maxsize)
            if fetch_num > 1 then
                seeds.components.stackable:SetStackSize(fetch_num)
            end
        end
        -- 消耗
        self.map[prefab] = math.max(0,cur_num - fetch_num)
        self.info = prefab .. '|' .. self.map[prefab]
        return seeds
    end
    return nil
end

function webbert_seedbox:ForceSync()
    local parts = {}
    for k, v in pairs(self.map or {}) do
        self.map[k] = v
        table.insert(parts, k)
        table.insert(parts, tostring(v))
    end
    self.info = table.concat(parts, "|")
end

return webbert_seedbox